package com.fitbet.wechat.handler.impl;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.entity.auth.WebAuthLogin;
import com.fitbet.wechat.handler.AutoLoginHandler;
import com.fitbet.wechat.rao.AutoLoginRao;

/**
 * 
 * @author wangliwang
 *
 */
@Component("autoLoginHandler")
public class AutoLoginHandlerImpl implements AutoLoginHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(AutoLoginHandlerImpl.class);
    
    @Value("#{ctx['api.host']}")
    private String host;
    
    @Rao
    private AutoLoginRao autoLoginRao;

    /*
     * (non-Javadoc)
     * @see com.edoomath.site.handler.AutoLoginHandler#login(com.demo2do.core.wechat.entity.auth.WebAuthLogin)
     */
    public Map<String, Object> login(WebAuthLogin login) {

        try {
            
            String uri = com.demo2do.core.utils.StringUtils.connect(host, "/users");
            
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("nickname", login.getNickname());
            parameters.put("avatar", login.getAvatar());
            parameters.put("unionid", login.getUnionid());
            parameters.put("openid", login.getOpenid());
            
            logger.info("#getUserInfo() - start call api with url[{}] parameters[{}]", uri, JsonUtils.toJson(parameters));
            HttpResult httpResult = autoLoginRao.login(uri, parameters);
            
            logger.info("#getUserInfo() - [{}]", JsonUtils.toJson(httpResult));
            
            // whether response is success
            if (!httpResult.isValid()) {
                logger.error("#getUserInfo() - remote api occur exception, [{}]", httpResult.getMessage());
                throw BusinessException.newInstance("500", "远程Api接口出错");
            }
            
            return httpResult.getData();
            
        } catch (Exception e) {
            logger.error("#getUserInfo() - call api occur exception, [{}]", e);
            throw BusinessException.newInstance("500", "调用Api接口出错");
        }
        
    }
}
